﻿@model ClarizenGadget.Models.DocumentViewModel
           
<link href="../../Content/DocumentsTab.css" rel="stylesheet" type="text/css" />
  
        <div class="DocumentList">
            <div class="buttonRow">
                <input type="button" value="+ Add a Document" id='openAdd' />
            </div>
        </div>

        <div class="NewDocument" style="display:none;zoom:1">
                <div class="Title">
                    Add a Document
                    <input type="hidden" id="TaskID" name="TaskID"/>
                    <input type="hidden" id="DocID" name="ID.Value"/>
                </div>
                <div class="Body">
                    <div class="Row">
                        <div class="Property"> 
                            <div class="Label">Add From</div>
                            <select id="documentType" name="Type">
                                <option value="URL">Web Page</option>
                                <option value="Google">Google docs</option>
                                <option value="Path">Shortcut</option>
                                <option value="Upload">Upload</option>
                            </select>
                        </div>
                        <div class="Property" style="width:300px">
                            <div class="Label">Path</div>
                            <input  type="file" name="Path" style="display:none"/>
                            <input  type="text" name="Url" style="vertical-align:top" />
                            <input  type="button" value="Search" id="btnSearchGoogle" style="display:none" />
                            <span style="display:none" id="uploadContainer">
                                <input  type="file" value="Search" id="file_upload"/>
                            </span>
                        </div>
                    </div>
                    <div class="Row">
                        <div class="Property Name">
                            <div class="Label">Name</div>
                            <input  type="text" name="Name"/>
                        </div>
                        <div class="Property">
                            <div class="Label">Document Type</div>
                            @Html.DropDownList("DocumentTypeID", Model.DocumentTypes.Select(u => new SelectListItem { Text = u.Name, Value = u.Id.Value, Selected = u.Name == Logic.Constants.DefaultDocumentType }))
                        </div>
                    </div>
                    <div class="Row">
                        <div class="Property">
                            <div class="Label">Description</div>
                            <textarea name="Description"></textarea>
                        </div>
                    </div>
                     <div class="Row buttonRow">
                        <span type='button' class="Link" id="cancel" >Cancel</span>
                        <input type='button' value='Create' id="createDoc"/>
                      </div>
                     <div class="Row"></div>
                </div>
        </div>



<script type="text/javascript">
    var UPLOAD = "Upload";

    $(document).ready(function ()
    {
        $('#openAdd').click(function ()
        {
            $('#createDoc').attr('value', "Create");
            $('#DocID').val("");
            $('.DocumentList').hide();
            $('.NewDocument').show();

            var c = $('.NewDocument');
            c.find('[name="Path"]').val('');
            c.find('[name="Url"]').val('');
            c.find('[name="Name"]').val('');
        });

        $('#cancel').click(function ()
        {
            $('.NewDocument').hide();
            $('.DocumentList').show();
        });

        $('#createDoc').click(function ()
        {
            
            var doc = {};
            $("input, textarea, select", '.NewDocument').each(function ()
            {
                doc[this.name] = $(this).val();
            });

            if(!doc.Url)
            {
                alert("First select a document.");
                return;
            }

            $('.NewDocument').show_loading(true);

            if ($('#documentType').val() == UPLOAD)
            {
                doc.ASPSESSID = "@Session.SessionID";
                $('#file_upload').uploadifySettings('scriptData', doc);
                $('#file_upload').uploadifyUpload();

                return;
            }

            else remoteRequest({
                url: stringFormat("@(Logic.Constants.CurrentUrl)/Documents/Create"),
                contentType: "JSON",
                type: "POST",
                data: $("input, textarea, select", '.NewDocument').serialize(),
                success: function (data)
                {
                    if(data.Data)
                    {
                        $('.NewDocument').show_loading(false);
                        addDocument($.extend(doc, data.Data));
                        $('.NewDocument').hide();
                        $('.DocumentList').show();
                    }
                    else
                    {
                        alert(data.ErrorMessage);
                        $('.NewDocument').show_loading(false);
                    }
                }
            });
        });

        $('#documentType').change(function ()
        {
            $('#btnSearchGoogle').hide();
            $('[name="Path"]').hide();
            $('[name="Url"]').hide();
            $('#uploadContainer').hide();


            switch ($('#documentType').val())
            {
                case "Google":
                    $('#btnSearchGoogle').show();
                    $('[name="Url"]').show();
                    break;
                case "URL":
                case "Path":
                    $('[name="Url"]').show();
                    break;
                case UPLOAD:
                    $('[name="Url"]').show();
                    $('#uploadContainer').show();
                    break;
            }

            $('[name="Url"]').val("");
            $('[name="Path"]').val("");

        });

        $('[name="Path"]').change(function ()
        {
            $('[name="Url"]').val($(this).val());

            if(!$('.NewDocument [name="Name"]').val())
                $('.NewDocument [name="Name"]').val($(this).val());
        });

        $('[name="Url"]').change(function ()
        {
            debugger;
            if(!$('.NewDocument [name="Name"]').val())
                $('.NewDocument [name="Name"]').val($(this).val());
        });

        Attach();
        $('#file_upload').uploadify({
            'uploader': '/uploadify/uploadify.swf',
            'script': '/Documents/Create',
            'cancelImg': '/uploadify/cancel.png',
            'folder': '/uploads',
            'auto': false,
            width: 78,
            height: 32,
            buttonImg: "/Images/General/Button.png",
            buttonText: "Select",
            //hideButton: true,
            onSelect: function (event, ID, fileObj)
            {
                $('[name="Url"]').val(fileObj.name);
            },
            onComplete: function (event, ID, fileObj, response, data)
            {
                var d = jQuery.parseJSON(response);
                addDocument(d.Data);
                $('.NewDocument').hide();
                $('.DocumentList').show();
                $('.NewDocument').show_loading(false);
            } //,
            
        });

    });

    function Attach(container)
    {
        $('.Delete', container).click(function ()
        {
            var el = $(this).closest('.Document');
            var doc = el.data('doc');
            el.show_loading(true);
            remoteRequest({
                    url: stringFormat("@(Logic.Constants.CurrentUrl)/Documents/Delete"),
                    contentType: "JSON",
                    type: "POST",
                    data: {docID: doc.ID.Value, linkID: doc.LinkID},
                    success: function (data)
                    {
                        if(data.Data)
                            el.fadeOut(function () { el.remove(); });
                        else
                            alert(el.ErrorMessage)
                    }
                });
            
        });

        $('.Edit', container).click(function ()
        {
            var el = $(this).closest('.Document');
            var doc = el.data('doc');
            $('.DocumentList').hide();
            $('.NewDocument').show();

            $(stringFormat(".NewDocument [name='{0}']", "Name")).val(htmlUnEscape(doc["Name"]));
            $(stringFormat(".NewDocument [name='{0}']", "DocumentTypeID")).val(htmlUnEscape(doc["DocumentTypeID"])).ddl('set');
            $(stringFormat(".NewDocument [name='{0}']", "Description")).val(htmlUnEscape(doc["Description"]));
            $(stringFormat(".NewDocument [name='{0}']", "Path")).val('');
            $(stringFormat(".NewDocument [name='{0}']", "Url")).val('');

            $('#DocID').val(doc.ID.Value);
            $('#createDoc').attr('value', "Update");
        });
    }

    function addDocument(doc)
    {
        var docDiv = $($.jqote($(".DocumentTmpl"), doc));
        if($("#" + doc.ID.Value).length)
            $("#" + doc.ID.Value).replaceWith(docDiv);
        else
            $('.DocumentList').append(docDiv);
        docDiv.data('doc', doc);
        Attach(docDiv);
    }

    var hasGoogleAuth = @Model.AuthorizedGoogle.ToString().ToLower();
    $('#btnSearchGoogle').click(function ()
    {
        if(hasGoogleAuth)
            loadDocumentTree();
        else
        {
            var url = "@Logic.Constants.CurrentUrl/Google/Oauth";

            if(window.showModalDialog)
                window.showModalDialog(url, window, "dialogHeight:300px;dialogWidth:500px;center:yes;resizable:yes");
            else window.open(url, "Oauth", "width:500px,height:300px");

            window.googleLoggedIn = function(success)
            {
                if(success)
                {
                    hasGoogleAuth = true;
                    loadDocumentTree();
                }
            }
        }
    });


    function loadDocumentTree()
    {
        var modalString = '\
            <div id="dialog-modal" title="Attach google Document">\
                <div id="treeContainer"></div>\
            </div>';

        var div = $(modalString);
        div.find("#treeContainer").treeview({
            loadFunction: function (id, callback)
            {
                var data = {};
                if (id && id.length > 10)
                    data.url = id;
                remoteRequest({
                    url: stringFormat("@(Logic.Constants.CurrentUrl)/Google/Documents"),
                    contentType: "JSON",
                    type: "POST",
                    data: data,
                    success: function (data)
                    {
                        callback(data.Data);
                    }
                });
            }
        });

        var buttons = [
            {
                text: "Select",
                click: function ()
                {
                    var url = $('[type=radio]:checked', div).closest('li').attr('id');
                    $('[name="Url"]').val(url);
                    $(this).dialog("close");
                }
            },
            {
                text: "Cancel",
                click: function () { $(this).dialog("close"); }
            }];

        div.dialog({
            height: Math.min(460, $(window).height() - 60),
            width: Math.min($(window).width() - 30, 400),
            modal: true,
            buttons: buttons,
            close: function ()
            {

            }
        });
    }
    
    function getDocumentsData()
    {
        return $(".DocumentList .Document").map(function (idx, el)
        {
            return stringFormat("&Documents[{0}].ID.Value={1}", idx, $(el).data('doc').ID.Value)
        }).toArray().join("");
    }

</script>

<script type="text/html" class="Templates DocumentTmpl">
     <![CDATA[
        <div class="Document Row RemoveOnSave" id="<%=this.ID.Value%>">
            <div class="Name"><%=this.CreatedBy_Name%></div>
            <div class="Box">
                <div class="DocName">
                    <span class="Img16 Doc"></span>
                    <a class='link' target="_blank" href="<%=stringFormat("@Logic.Constants.ClarizenEntityUrlFormat", this.ID.Value, this.ID.TypeName)%>"><%=this.Name%></a>
                    <span class="Img16 Delete"></span>
                    <span class="Img16 Edit"></span>
                </div>
            </div>
        </div>
    ]]>
</script>
